<template>
  <div class="captcha-container" @click="refreshCaptcha">
    <div class="captcha-display">
      <span
        v-for="(char, index) in captchaText"
        :key="index"
        :style="getCharStyle(index)"
        class="captcha-char"
      >
        {{ char }}
      </span>
    </div>
    <div class="captcha-tip">点击更换验证码</div>
  </div>
</template>

<script setup>
import { ref, onMounted } from "vue";

// 验证码长度
const CAPTCHA_LENGTH = 4;

// 验证码文本
const captchaText = ref("");

// 生成随机数字验证码
const generateCaptcha = () => {
  let captcha = "";
  for (let i = 0; i < CAPTCHA_LENGTH; i++) {
    captcha += Math.floor(Math.random() * 10); // 0-9的随机数
  }
  captchaText.value = captcha;
};

// 刷新验证码
const refreshCaptcha = () => {
  generateCaptcha();
  // 可以在这里emit事件通知父组件验证码已更新
  emit("update", captchaText.value);
};

// 为每个字符生成随机样式
const getCharStyle = () => {
  return {
    color: getRandomColor(),
    transform: `rotate(${Math.random() * 20 - 10}deg)`,
    fontSize: `${20 + Math.random() * 10}px`,
    display: "inline-block",
    margin: "0 2px",
    fontWeight: "bold"
  };
};

// 生成随机颜色
const getRandomColor = () => {
  const letters = "0123456789ABCDEF";
  let color = "#";
  for (let i = 0; i < 6; i++) {
    color += letters[Math.floor(Math.random() * 16)];
  }
  return color;
};

// 定义emit
const emit = defineEmits(["update"]);

// 组件挂载时生成初始验证码
onMounted(() => {
  generateCaptcha();
  emit("update", captchaText.value);
});

// 暴露刷新方法，父组件可以调用
defineExpose({
  refreshCaptcha
});
</script>

<style scoped>
.captcha-container {
  display: inline-block;
  cursor: pointer;
  user-select: none;
  text-align: center;
}

.captcha-display {
  background-color: #f5f5f5;
  padding: 10px 20px;
  border-radius: 4px;
  display: inline-block;
  margin-bottom: 5px;
  border: 1px solid #ddd;
}

.captcha-char {
  transition: all 0.3s ease;
}

.captcha-tip {
  font-size: 12px;
  color: #999;
}
</style>